﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Linq;
using System.Threading.Tasks;

namespace MetaSharp.Transformation.Patterns
{
    public class OrPattern : Pattern
    {
        public IEnumerable<Pattern> Patterns { get; private set; }
        public OrPattern(IEnumerable<Pattern> patterns)
            : base(PatternKind.Or)
        {
            this.Patterns = patterns;
        }

        public override PatternMatch Compile()
        {
            var patterns = new List<PatternMatch>();
            foreach (var pattern in Patterns)
                patterns.Add(pattern.Compile());

            return s => Target(s, patterns);
        }

        private static async Task<IMatch> Target(IScope scope, IEnumerable<PatternMatch> patterns)
        {
            var states = patterns.Select(pattern => pattern(scope));
            foreach (var state in states)
            {
                var result = await state;
                if (result.Matched || result.IsLR)
                    return result;
            }

            return await Transformation.Match.Fail(scope);
        }
    }
}
